/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.financial.web.billnegotiated;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.base.dao.investorfinancialinfo.NegotiatedInterestDao;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.CustomerPrice;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.fixedexpense.SupplierPrice;
import com.jeesite.modules.base.entity.investorfinancialinfo.InvestorFinancialInfo;
import com.jeesite.modules.base.entity.investorfinancialinfo.NegotiatedInterest;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.investorfinancialinfo.InvestorFinancialInfoService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.AccountType;
import com.jeesite.modules.financial.dao.billnegotiated.BillNegotiatedDao;
import com.jeesite.modules.financial.dao.billnegotiated.BillNegotiatedDetailDao;
import com.jeesite.modules.financial.entity.billnegotiated.BillNegotiated;
import com.jeesite.modules.financial.entity.billnegotiated.BillNegotiatedDetail;
import com.jeesite.modules.financial.entity.lettercredit.LetterCredit;
import com.jeesite.modules.financial.entity.lettercredit.LetterCreditDetail;
import com.jeesite.modules.financial.service.billnegotiated.BillNegotiatedService;
import com.jeesite.modules.financial.service.lettercredit.LetterCreditService;
import com.jeesite.modules.logistics.dao.ladingbill.LadingBillDetailDao;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBill;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBillDetail;
import com.jeesite.modules.logistics.service.ladingbill.LadingBillService;
import com.jeesite.modules.order.dao.serviceorder.ServiceOrderDetailDao;
import com.jeesite.modules.order.entity.serviceorder.RelatedRecord;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 到单押汇Controller
 * @author Kilo
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/financial/billnegotiated/billNegotiated")
public class BillNegotiatedController extends BaseController {

	@Autowired
	private BillNegotiatedService billNegotiatedService;
	@Autowired
	private LadingBillService ladingBillService;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private InvestorFinancialInfoService investorFinancialInfoService;
	@Autowired
	private ServiceOrderDetailDao serviceOrderDetailDao;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private NegotiatedInterestDao negotiatedInterestDao;
	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private LadingBillDetailDao ladingBillDetailDao;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private BillNegotiatedDao billNegotiatedDao;
	@Autowired
	private LetterCreditService letterCreditService;
	@Autowired
	private TapService tapService;
	@Autowired
	private TarService tarService;
	@Autowired
	private TprepaymentService tprepaymentService;
	@Autowired
	private TadvancesReceivedService tadvancesReceivedService;
	@Autowired
	private BillNegotiatedDetailDao billNegotiatedDetailDao;
	@Autowired
	private FixedExpenseService fixedExpenseService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public BillNegotiated get(String billNegotiatedId, boolean isNewRecord) {
		return billNegotiatedService.get(billNegotiatedId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:view")
	@RequestMapping(value = {"list", ""})
	public String list(BillNegotiated billNegotiated, Model model) {
		model.addAttribute("billNegotiated", billNegotiated);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		model.addAttribute("listUser", empUserService.findList(new EmpUser()));
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		model.addAttribute("frameNumberList", ladingBillDetailDao.findList(new LadingBillDetail()));
		return "modules/financial/billnegotiated/billNegotiatedList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<BillNegotiated> listData(BillNegotiated billNegotiated, HttpServletRequest request, HttpServletResponse response) {
		billNegotiated.setPage(new Page<>(request, response));
		Page<BillNegotiated> page = billNegotiatedService.findPage(billNegotiated);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:view")
	@RequestMapping(value = "form")
	public String form(BillNegotiated billNegotiated, Model model) {
		List<BillNegotiatedDetail> billNegotiatedDetailList1 = ListUtils.newArrayList();
		List<BillNegotiatedDetail> billNegotiatedDetailList2 = ListUtils.newArrayList();
		List<BillNegotiatedDetail> billNegotiatedDetailList = billNegotiated.getBillNegotiatedDetailList();
		for (BillNegotiatedDetail billNegotiatedDetail : billNegotiatedDetailList) {
			if("1".equals(billNegotiatedDetail.getType())){
				billNegotiatedDetailList1.add(billNegotiatedDetail);
			} else if("2".equals(billNegotiatedDetail.getType())){
				billNegotiatedDetailList2.add(billNegotiatedDetail);
			}
		}

		billNegotiated.setBillNegotiatedDetailList1(billNegotiatedDetailList1);
		billNegotiated.setBillNegotiatedDetailList2(billNegotiatedDetailList2);
		model.addAttribute("billNegotiated", billNegotiated);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		model.addAttribute("listUser", empUserService.findList(new EmpUser()));
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		LadingBill bill = ladingBillService.get(billNegotiated.getLadingBillId());
		List<LadingBillDetail> frameNumberList = bill.getLadingBillDetailList();
		model.addAttribute("frameNumberList", frameNumberList);
		model.addAttribute("listPrepayment", tprepaymentService.findList(new Tprepayment()));
		model.addAttribute("listAp", tapService.findList(new Tap()));
		model.addAttribute("listAdvancesReceived", tadvancesReceivedService.findList(new TadvancesReceived()));
		model.addAttribute("listAr", tarService.findList(new Tar()));
		model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
		return "modules/financial/billnegotiated/billNegotiatedForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:view")
	@RequestMapping(value = "detail")
	public String detail(BillNegotiated billNegotiated, Model model) throws ParseException {
		Double negotiatedAmount = billNegotiated.getNegotiatedAmount(); // 押汇金额
        String investorNegotiatedPlan = billNegotiated.getInvestorNegotiatedPlan();// 资方押汇方案
        InvestorFinancialInfo investorFinancialInfo = investorFinancialInfoService.get(investorNegotiatedPlan);
        Integer supplierYearRateCode = 0;
        Integer customerYearRateCode = 0;
        for (NegotiatedInterest negotiatedInterest : investorFinancialInfo.getNegotiatedInterestList()) {
            if ("1".equals(negotiatedInterest.getStageType()) && supplierYearRateCode == 0){
                billNegotiated.setSupplieryearrate(negotiatedInterest.getInvestorInterestRatio());
                supplierYearRateCode++;
            }
            if ("2".equals(negotiatedInterest.getStageType()) && customerYearRateCode == 0){
                billNegotiated.setCustomeryearrate(negotiatedInterest.getCustomerInterestRatio());
                customerYearRateCode++;
            }
        }

        if(negotiatedAmount !=  null){
			Double investorInterestRatio = NumberUtils.div(Double.parseDouble(billNegotiated.getInvestorInterestRatio()), 100); //资方正常利率
			Double customerInterestRatio = NumberUtils.div(Double.parseDouble(billNegotiated.getCustomerInterestRatio()), 100); //客户正常利率
			Long investorYearDays = billNegotiated.getInvestorYearDays(); // 资方年天数
			Double investorDays = 0D; // 资方天数差
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date now = df.parse(df.format(new Date()));
			if(now.compareTo(billNegotiated.getInvestorEndDate()) >= 0){
				investorDays = DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(), billNegotiated.getInvestorEndDate());
			} else {
				investorDays = DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(), now);
			}
			Double customerDays = 0D; // 客户天数差
			if(now.compareTo(billNegotiated.getCustomerEndDate()) >= 0){
				customerDays = DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(), billNegotiated.getCustomerEndDate());
			} else {
				customerDays = DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(), now);
			}
			Double amount = 0D; // 资方押汇期应还款利息
			Double customerAmount = 0D; // 客户押汇期应还款利息
			if(investorDays != 0){
			    if ("1".equals(billNegotiated.getN1Flag())){
                    investorDays++;
                }
				amount = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, investorInterestRatio),investorYearDays), investorDays);
			}
			if(customerDays != 0){
                if ("1".equals(billNegotiated.getN1Flag())){
                    customerDays++;
                }
				customerAmount = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, customerInterestRatio),360), customerDays);
			}
			billNegotiated.setAmount(amount);
			billNegotiated.setCustomerAmount(customerAmount);

			List<BillNegotiatedDetail> billNegotiatedDetailList = billNegotiated.getBillNegotiatedDetailList();
			List<BillNegotiatedDetail> billNegotiatedDetailList1 = ListUtils.newArrayList();
			List<BillNegotiatedDetail> billNegotiatedDetailList2 = ListUtils.newArrayList();
			Double investorInterestTotal = 0D;//资方利息合计
			Double customerInterestTotal = 0D;//客户利息合计
//			Double benjin =billNegotiated.getNegotiatedAmount();
			for (BillNegotiatedDetail billNegotiatedDetail : billNegotiatedDetailList) {
				if("1".equals(billNegotiatedDetail.getType())){
					Double investorDetailRatio = NumberUtils.div(Double.parseDouble(billNegotiatedDetail.getNegotiatedRate()), 100); //资方利率
					Double investorDetailDays = 0D;
					if(now.compareTo(billNegotiatedDetail.getStartDate()) >= 0 && now.compareTo(billNegotiatedDetail.getEndDate()) <= 0){
						investorDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), now);
					} else if(now.compareTo(billNegotiatedDetail.getStartDate()) >= 0 && now.compareTo(billNegotiatedDetail.getEndDate()) > 0){
						investorDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiatedDetail.getEndDate());
					}
					Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, investorDetailRatio),investorYearDays), investorDetailDays);
                    BigDecimal b = new BigDecimal(interest);
                    interest = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
					billNegotiatedDetail.setNegotiatedInterest(interest);
					billNegotiatedDetailList1.add(billNegotiatedDetail);
					investorInterestTotal = NumberUtils.add(investorInterestTotal, interest);
				} else if("2".equals(billNegotiatedDetail.getType())){
					Double customerDetailRatio = NumberUtils.div(Double.parseDouble(billNegotiatedDetail.getNegotiatedRate()), 100); //客户利率
					Double customerDetailDays = 0D;
					if(now.compareTo(billNegotiatedDetail.getStartDate()) >= 0 && now.compareTo(billNegotiatedDetail.getEndDate()) <= 0){
						customerDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), now);
					} else if(now.compareTo(billNegotiatedDetail.getStartDate()) >= 0 && now.compareTo(billNegotiatedDetail.getEndDate()) > 0){
						customerDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiatedDetail.getEndDate());
					}
					Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, customerDetailRatio),360), customerDetailDays);
                    BigDecimal b = new BigDecimal(interest);
                    interest = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
					billNegotiatedDetail.setNegotiatedInterest(interest);
					billNegotiatedDetailList2.add(billNegotiatedDetail);
					customerInterestTotal = NumberUtils.add(customerInterestTotal, interest);
				}
			}
//		billNegotiated.setInvestorNegotiatedInterest(NumberUtils.add(investorInterestTotal, amount));
//		billNegotiated.setInvestorTotalPrincipalInterest(NumberUtils.add(NumberUtils.add(investorInterestTotal, benjin), amount));
//		billNegotiated.setCustomerNegotiatedInterest(NumberUtils.add(customerInterestTotal, customerAmount));
//		billNegotiated.setCustomerTotalPrincipalInterest(NumberUtils.add(NumberUtils.add(customerInterestTotal, benjin), customerAmount));
			billNegotiated.setBillNegotiatedDetailList1(billNegotiatedDetailList1);
			billNegotiated.setBillNegotiatedDetailList2(billNegotiatedDetailList2);
		}

		// 相关记录
		List<RelatedRecord> relatedRecordList = ListUtils.newArrayList();
		// 应收单
		Tar tar = new Tar();
		tar.setParentBillCode(billNegotiated.getBillNegotiatedId());
		List<Tar> list = tarService.findList(tar);
		for (Tar tar1 : list) {
			for (TarDetail tarDetail : tarService.get(tar1).getTarDetailList()) {
				RelatedRecord relatedRecord = new RelatedRecord();
				relatedRecord.setBillCode(tar1.getArCode());
				relatedRecord.setDate(tar1.getDate());
				relatedRecord.setExpenseItem(fixedExpenseService.get(tarDetail.getExpenseItem()).getFixedExpenseName());
				relatedRecord.setYingshouAmount(tarDetail.getApAmount());
				relatedRecordList.add(relatedRecord);
			}
		}
		// 应付单
		Tap tap = new Tap();
		tap.setParentBillCode(billNegotiated.getBillNegotiatedId());
		List<Tap> list1 = tapService.findList(tap);
		for (Tap tap1 : list1) {
			for (TapDetail tapDetail : tapService.get(tap1).getTapDetailList()) {
				RelatedRecord relatedRecord = new RelatedRecord();
				relatedRecord.setBillCode(tap1.getApCode());
				relatedRecord.setDate(tap1.getDate());
				relatedRecord.setExpenseItem(fixedExpenseService.get(tapDetail.getExpenseItem()).getFixedExpenseName());
				relatedRecord.setYingfuAmount(tapDetail.getApAmount());
				relatedRecordList.add(relatedRecord);
			}
		}

		// 预收单
		TadvancesReceived tadvancesReceived = new TadvancesReceived();
		tadvancesReceived.setParentBillCode(billNegotiated.getBillNegotiatedId());
		List<TadvancesReceived> list4 = tadvancesReceivedService.findList(tadvancesReceived);
		for (TadvancesReceived tadvancesReceived1 : list4) {
			for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedService.get(tadvancesReceived1).getTadvancesReceivedEstimatedList()) {
				RelatedRecord relatedRecord = new RelatedRecord();
				relatedRecord.setBillCode(tadvancesReceived1.getAdvancesReceivedCode());
				relatedRecord.setDate(tadvancesReceived1.getDate());
				relatedRecord.setExpenseItem(fixedExpenseService.get(tadvancesReceivedEstimated.getAdvancesReceivedType()).getFixedExpenseName());
				relatedRecord.setYushouAmount(tadvancesReceivedEstimated.getEstimatedReceivedAmount());
				relatedRecordList.add(relatedRecord);
			}
		}

		// 预付单
		Tprepayment tprepayment = new Tprepayment();
		tprepayment.setParentBillCode(billNegotiated.getBillNegotiatedId());
		List<Tprepayment> list5 = tprepaymentService.findList(tprepayment);
		for (Tprepayment tprepayment1 : list5) {
			for (TprepaymentEstimated tprepaymentEstimated : tprepaymentService.get(tprepayment1).getTprepaymentEstimatedList()) {
				RelatedRecord relatedRecord = new RelatedRecord();
				relatedRecord.setBillCode(tprepayment1.getPrepaymentCode());
				relatedRecord.setDate(tprepayment1.getDate());
				relatedRecord.setExpenseItem(fixedExpenseService.get(tprepaymentEstimated.getPrepaymentType()).getFixedExpenseName());
				relatedRecord.setYushouAmount(tprepaymentEstimated.getEstimatedPaymentAmount());
				relatedRecordList.add(relatedRecord);
			}
		}
		billNegotiated.setRelatedRecordList(relatedRecordList);
		model.addAttribute("billNegotiated", billNegotiated);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		LadingBill bill = ladingBillService.get(billNegotiated.getLadingBillId());
		List<LadingBillDetail> frameNumberList = bill.getLadingBillDetailList();
		model.addAttribute("frameNumberList", frameNumberList);
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		model.addAttribute("listPrepayment", tprepaymentService.findList(new Tprepayment()));
		model.addAttribute("listAp", tapService.findList(new Tap()));
		model.addAttribute("listAdvancesReceived", tadvancesReceivedService.findList(new TadvancesReceived()));
		model.addAttribute("listAr", tarService.findList(new Tar()));
		model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
		return "modules/financial/billnegotiated/billNegotiatedDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated BillNegotiated billNegotiated) {
		List<BillNegotiatedDetail> billNegotiatedDetailList1 = billNegotiated.getBillNegotiatedDetailList1();
		List<BillNegotiatedDetail> billNegotiatedDetailList2 = billNegotiated.getBillNegotiatedDetailList2();
		List<BillNegotiatedDetail> list = ListUtils.newArrayList();
		list.addAll(billNegotiatedDetailList1);
		list.addAll(billNegotiatedDetailList2);
		billNegotiated.setBillNegotiatedDetailList(list);
		billNegotiatedService.save(billNegotiated);
		return renderResult(Global.TRUE, text("保存到单押汇成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(BillNegotiated billNegotiated) {
		billNegotiatedService.delete(billNegotiated);
		return renderResult(Global.TRUE, text("删除到单押汇成功！"));
	}

    /**
     * 车架号对象
     */
	class FrameNumberObj{
        private String frameNumber;
        public String getFrameNumber() {
            return frameNumber;
        }
        public void setFrameNumber(String frameNumber) {
            this.frameNumber = frameNumber;
        }
    }

	/**
	 * 提单到单押汇按钮
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "goBillNegotiated")
	public String goBillNegotiated(LadingBill ladingBill, Model model) {
		LadingBill bill = ladingBillService.get(ladingBill);
		List<LadingBillDetail> frameNumberArrayList = bill.getLadingBillDetailList();
        List < String > frameNumberList = ListUtils.newArrayList();
        for (LadingBillDetail ladingBillDetail : frameNumberArrayList) {
            if (StringUtils.isNotEmpty(ladingBillDetail.getFrameNumber())){
                frameNumberList.add(ladingBillDetail.getFrameNumber());
            }
        }
        // 查到单押汇生效的车架号
        BillNegotiated billNegotiated1 = new BillNegotiated();
        billNegotiated1.setStatus1("1"); // 1生效  2作废
        List < BillNegotiated > listBillNegotiated = billNegotiatedService.findList(billNegotiated1);
        // 提单中车架号在到单押汇中已生效
        List<String> arrayList = ListUtils.newArrayList();
        for (LadingBillDetail ladingBillDetail : frameNumberArrayList) {
            for (BillNegotiated billNegotiated : listBillNegotiated) {
                if (StringUtils.isNotEmpty(ladingBillDetail.getFrameNumber()) && ladingBillDetail.getFrameNumber().equals(billNegotiated.getFrameNumber())){
                    arrayList.add(ladingBillDetail.getFrameNumber());
                }
            }
        }
        // frameNumberList 中去除 arrayList
        frameNumberList.removeAll(arrayList);
        // 转换成list对象
        List<FrameNumberObj> list = ListUtils.newArrayList();
        for (String s : frameNumberList) {
            FrameNumberObj frameNumberObj = new FrameNumberObj();
            frameNumberObj.setFrameNumber(s);
            list.add(frameNumberObj);
        }
        model.addAttribute("frameNumberList", list);
		BillNegotiated billNegotiated = new BillNegotiated();
		ServiceOrder so = serviceOrderService.get(bill.getServiceOrder());
		billNegotiated.setLetterCreditCode(so.getLetterCreditCode());
		billNegotiated.setServiceOrderCode(so.getServiceOrderId());
		billNegotiated.setEntrustAgreement(so.getPurchaseCommissionNumber());
		billNegotiated.setCustomer(so.getCustomer());
		billNegotiated.setInvestorId(so.getInvestorId());
		billNegotiated.setForeignTradeContractNumber(so.getForeignTradeContractNumber());
		billNegotiated.setNegotiatedRatio(so.getNegotiatedRatioId());
		billNegotiated.setCurrency(so.getCurrency());
		billNegotiated.setTentativeExchangeRate(so.getTentativeExchangeRate());
		InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
		investorFinancialInfo.setSupplier(so.getInvestor());
		investorFinancialInfo.setFinancingType("1");
		InvestorFinancialInfo info = investorFinancialInfoService.findList(investorFinancialInfo).get(0);
		billNegotiated.setInvestorYearDays(info.getDays());
		billNegotiated.setStatus1("1");
		billNegotiated.setLadingBillId(ladingBill.getLadingBillId());
		model.addAttribute("billNegotiated", billNegotiated);
		// 国内资方
		Supplier gnzf = new Supplier();
		gnzf.setSupplierType("1");
		List<Supplier> gnzfList = supplierService.findList(gnzf);
		model.addAttribute("gnzfList", gnzfList);
		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
		model.addAttribute("listPrepayment", tprepaymentService.findList(new Tprepayment()));
		model.addAttribute("listAp", tapService.findList(new Tap()));
		model.addAttribute("listAdvancesReceived", tadvancesReceivedService.findList(new TadvancesReceived()));
		model.addAttribute("listAr", tarService.findList(new Tar()));
		model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));
		return "modules/financial/billnegotiated/billNegotiatedForm";
	}

	/**
	 * 获取车辆信息
	 * @param frameNumber
	 */
	@RequestMapping(value = "getCarInfo")
	@ResponseBody
	public ServiceOrderDetail getCarInfo(@RequestParam("frameNumber") String frameNumber) {
		ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
		serviceOrderDetail.setFrameNumber(frameNumber);
		ServiceOrderDetail detail = serviceOrderDetailDao.findList(serviceOrderDetail).get(0);
		return detail;
	}

	/**
	 * 获取资方金融费率
	 * @param id
	 */
	@RequestMapping(value = "getInvestorFinancialInfo")
	@ResponseBody
	public InvestorFinancialInfo getInvestorFinancialInfo(@RequestParam("id") String id) {
		InvestorFinancialInfo info = investorFinancialInfoService.get(id);
//		List<NegotiatedInterest> collect = negotiatedInterestDao.findList(new NegotiatedInterest(info));
		info.setNegotiatedInterestList1(negotiatedInterestDao.findList(new NegotiatedInterest(info)).stream().filter(i -> "1".equals(i.getStageType())).collect(Collectors.toList()));
		info.setNegotiatedInterestList2(negotiatedInterestDao.findList(new NegotiatedInterest(info)).stream().filter(i -> "2".equals(i.getStageType())).collect(Collectors.toList()));
//		info.setNegotiatedInterestList1(collect);
//		InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
//		investorFinancialInfo.setSupplier(new Supplier(investorId));
//		InvestorFinancialInfo info = investorFinancialInfoService.findList(investorFinancialInfo).get(0);
//		info.setNegotiatedInterestList1(negotiatedInterestDao.findList(new NegotiatedInterest(info)).stream().filter(i -> "1".equals(i.getStageType())).collect(Collectors.toList()));
//		info.setNegotiatedInterestList2(negotiatedInterestDao.findList(new NegotiatedInterest(info)).stream().filter(i -> "2".equals(i.getStageType())).collect(Collectors.toList()));
		return info;
	}

	/**
	 * 客户还汇按钮
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "customerRemittance")
	public String customerRemittance(BillNegotiated billNegotiated, Model model) {
		model.addAttribute("billNegotiated", billNegotiated);
		return "modules/financial/billnegotiated/customerRemittanceForm";
	}

	/**
	 * 资方还汇按钮
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "investorRemittance")
	public String investorRemittance(BillNegotiated billNegotiated, Model model) {
		model.addAttribute("billNegotiated", billNegotiated);
		return "modules/financial/billnegotiated/investorRemittanceForm";
	}

	/**
	 * 不符点按钮
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "discrepancies")
	public String discrepancies(BillNegotiated billNegotiated, Model model) {
		model.addAttribute("billNegotiated", billNegotiated);
		return "modules/financial/billnegotiated/discrepanciesForm";
	}

	/**
	 * 保证金确认按钮
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "marginConfirm")
	public String marginConfirm(BillNegotiated billNegotiated, Model model) {
		model.addAttribute("billNegotiated", billNegotiated);
		return "modules/financial/billnegotiated/marginConfirmForm";
	}

	/**
	 * 保存客户还汇信息
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@PostMapping(value = "customerRemittanceSave")
	@ResponseBody
	@Transactional(readOnly=false)
	public String customerRemittanceSave(BillNegotiated billNegotiated) {
//		billNegotiatedService.save(billNegotiated);
		BillNegotiated bill = billNegotiatedService.get(billNegotiated.getBillNegotiatedId());
		Double negotiatedAmount = NumberUtils.mul(bill.getNegotiatedAmount(), Double.parseDouble(billNegotiated.getCustomerRealExchangeRate())); // 押汇金额RMB=押汇金额*实际汇率
//		billNegotiated.setNegotiatedAmountRmb(negotiatedAmount);
		Double customerInterestRatio = NumberUtils.div(Double.parseDouble(bill.getCustomerInterestRatio()), 100); //客户正常利率
		Double customerDays = 0D; // 客户天数差
		if(billNegotiated.getCustomerActualRepaymentDate().compareTo(bill.getCustomerEndDate()) >= 0){
			customerDays = DateUtils.getDistanceOfTwoDate(bill.getStartDate(), bill.getCustomerEndDate());
		} else {
			customerDays = DateUtils.getDistanceOfTwoDate(bill.getStartDate(), billNegotiated.getCustomerActualRepaymentDate());
		}
		Double customerAmount = 0D; // 客户押汇期应还款利息
		if(customerDays != 0){
			customerAmount = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, customerInterestRatio),360), customerDays);
		}
		billNegotiated.setCustomerNegotiatedInterest(customerAmount);

		List<BillNegotiatedDetail> billNegotiatedDetailList = bill.getBillNegotiatedDetailList();
		Double customerDetailInterestTotal = 0D;//客户延期利息合计
//		Double benjin =bill.getNegotiatedAmountRmb();
		for (BillNegotiatedDetail billNegotiatedDetail : billNegotiatedDetailList) {
			if("2".equals(billNegotiatedDetail.getType())){
				Double customerDetailRatio = NumberUtils.div(Double.parseDouble(billNegotiatedDetail.getNegotiatedRate()), 100); //客户利率
				Double customerDetailDays = 0D;
				if(billNegotiated.getCustomerActualRepaymentDate().compareTo(billNegotiatedDetail.getStartDate()) >= 0 && billNegotiated.getCustomerActualRepaymentDate().compareTo(billNegotiatedDetail.getEndDate()) <= 0){
					customerDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiated.getCustomerActualRepaymentDate());
				} else if(billNegotiated.getCustomerActualRepaymentDate().compareTo(billNegotiatedDetail.getStartDate()) >= 0 && billNegotiated.getCustomerActualRepaymentDate().compareTo(billNegotiatedDetail.getEndDate()) > 0){
					customerDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiatedDetail.getEndDate());
				}
				Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, customerDetailRatio),360), customerDetailDays);
//				billNegotiatedDetail.setNegotiatedInterest(interest);
				customerDetailInterestTotal = NumberUtils.add(customerDetailInterestTotal, interest);
			}
		}
		billNegotiated.setCustomerNegotiatedYqInterest(customerDetailInterestTotal);
		billNegotiated.setCustomerActualDays((long) DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(),billNegotiated.getCustomerActualRepaymentDate()));
		Double customerTotalPrincipalInterest = NumberUtils.add(NumberUtils.add(customerDetailInterestTotal, negotiatedAmount), customerAmount);
		billNegotiated.setCustomerTotalPrincipalInterest(customerTotalPrincipalInterest);
		billNegotiatedService.save(billNegotiated);
		// 生成客户应收
		Tar ar = new Tar();
		ar.setCustomer(bill.getCustomer());
		ar.setCustomerId(bill.getCustomer().getCustomerId());
		ar.setDate(new Date());
		ar.setStatus1("1");
		ar.setBillStatus("2");// 已提交
		ar.setServiceOrderId(bill.getServiceOrderCode());
//		Double benjin = bill.getPrepaidAmount();
//		Double lixi = bill.getCustomerPadTaxInterest();
//		Double yanqilixi = bill.getCustomerPadTaxYqInterest();
		ar.setAmount(customerTotalPrincipalInterest);
		ar.setCurrency(bill.getCurrency());
		ar.setParentBillType("BillNegotiated");
		ar.setParentBillCode(bill.getBillNegotiatedId());
		List<TarDetail> list = ListUtils.newArrayList();
		for (BillNegotiatedDetail billNegotiatedDetail : bill.getBillNegotiatedDetailList()) {
			if ("2".equals(billNegotiatedDetail.getType())) {
				TarDetail detail = new TarDetail();
				detail.setCarId(bill.getCarId());
				detail.setFrameNumber(bill.getFrameNumber());
				detail.setExpenseItem("ITM00000006");
				detail.setApAmount(negotiatedAmount);
				detail.setBrand(bill.getBrand());
				detail.setArea(bill.getArea());
				detail.setModel(bill.getModel());
				list.add(detail);

				TarDetail detail1 = new TarDetail();
				detail1.setCarId(bill.getCarId());
				detail1.setFrameNumber(bill.getFrameNumber());
				detail1.setExpenseItem("ITM00000012");
				detail1.setApAmount(customerAmount);
				detail1.setBrand(bill.getBrand());
				detail1.setArea(bill.getArea());
				detail1.setModel(bill.getModel());
				list.add(detail1);

				TarDetail detail2 = new TarDetail();
				detail2.setCarId(bill.getCarId());
				detail2.setFrameNumber(bill.getFrameNumber());
				detail2.setExpenseItem("ITM00000038");
				detail2.setApAmount(customerDetailInterestTotal);
				detail2.setBrand(bill.getBrand());
				detail2.setArea(bill.getArea());
				detail2.setModel(bill.getModel());
				list.add(detail2);
			}
		}
		ar.setTarDetailList(list);
		tarService.save(ar);
		billNegotiated.setCustomerReceivableId(ar.getArId());
		billNegotiatedService.update(billNegotiated);
		return renderResult(Global.TRUE, text("客户还汇保存成功！"));
	}

	/**
	 * 保存资方还汇信息
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@PostMapping(value = "investorRemittanceSave")
	@ResponseBody
	@Transactional(readOnly=false)
	public String investorRemittanceSave(BillNegotiated billNegotiated) {
//		billNegotiatedService.save(billNegotiated);
		BillNegotiated bill = billNegotiatedService.get(billNegotiated.getBillNegotiatedId());
		Double negotiatedAmount = NumberUtils.mul(bill.getNegotiatedAmount(), Double.parseDouble(billNegotiated.getInvestorRealExchangeRate())); // 押汇金额RMB=押汇金额*实际汇率
		billNegotiated.setNegotiatedAmountRmb(negotiatedAmount);
		Double investorInterestRatio = NumberUtils.div(Double.parseDouble(bill.getInvestorInterestRatio()), 100); //资方正常利率
		Long investorYearDays = bill.getInvestorYearDays(); // 资方年天数
		Double investorDays = 0D; // 资方天数差
		if(billNegotiated.getInvestorActualRepaymentDate().compareTo(bill.getInvestorEndDate()) >= 0){
			investorDays = DateUtils.getDistanceOfTwoDate(bill.getStartDate(), bill.getInvestorEndDate());
		} else {
			investorDays = DateUtils.getDistanceOfTwoDate(bill.getStartDate(), billNegotiated.getInvestorActualRepaymentDate());
		}
		Double amount = 0D; // 资方押汇期应还款利息
		if(investorDays != 0){
			amount = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, investorInterestRatio),investorYearDays), investorDays);
		}
		billNegotiated.setInvestorNegotiatedInterest(amount);

		List<BillNegotiatedDetail> billNegotiatedDetailList = bill.getBillNegotiatedDetailList();
		Double investorDetailInterestTotal = 0D;//资方延期利息合计
//		Double benjin =bill.getNegotiatedAmountRmb();
		for (BillNegotiatedDetail billNegotiatedDetail : billNegotiatedDetailList) {
			if("1".equals(billNegotiatedDetail.getType())){
				Double investorDetailRatio = NumberUtils.div(Double.parseDouble(billNegotiatedDetail.getNegotiatedRate()), 100); //资方利率
				Double investorDetailDays = 0D;
				if(billNegotiated.getInvestorActualRepaymentDate().compareTo(billNegotiatedDetail.getStartDate()) >= 0 && billNegotiated.getInvestorActualRepaymentDate().compareTo(billNegotiatedDetail.getEndDate()) <= 0){
					investorDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiated.getInvestorActualRepaymentDate());
				} else if(billNegotiated.getInvestorActualRepaymentDate().compareTo(billNegotiatedDetail.getStartDate()) >= 0 && billNegotiated.getInvestorActualRepaymentDate().compareTo(billNegotiatedDetail.getEndDate()) > 0){
					investorDetailDays = DateUtils.getDistanceOfTwoDate(billNegotiatedDetail.getStartDate(), billNegotiatedDetail.getEndDate());
				}
				Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount, investorDetailRatio),investorYearDays), investorDetailDays);
//				billNegotiatedDetail.setNegotiatedInterest(interest);
				investorDetailInterestTotal = NumberUtils.add(investorDetailInterestTotal, interest);
			}
		}
		billNegotiated.setInvestorNegotiatedYqInterest(investorDetailInterestTotal);
		billNegotiated.setInvestorActualDays((long) DateUtils.getDistanceOfTwoDate(billNegotiated.getStartDate(),billNegotiated.getInvestorActualRepaymentDate()));
		Double investorTotalPrincipalInterest = NumberUtils.add(NumberUtils.add(investorDetailInterestTotal, negotiatedAmount), amount);
		billNegotiated.setInvestorTotalPrincipalInterest(investorTotalPrincipalInterest);
		billNegotiatedService.save(billNegotiated);
		// 生成资方应付
		Tap ap = new Tap();
		ap.setSupplierId(bill.getInvestorId());
		ap.setDate(new Date());
		ap.setStatus1("1");
		ap.setBillStatus("2");// 已提交
		ap.setServiceOrderId(bill.getServiceOrderCode());
//		Double benjin = taxClearance.getPrepaidAmount();
//		Double lixi = taxClearance.getCustomerPadTaxInterest();
//		Double yanqilixi = taxClearance.getCustomerPadTaxYqInterest();
		ap.setAmount(investorTotalPrincipalInterest);
		ap.setCurrency(bill.getCurrency());
		ap.setParentBillType("BillNegotiated");
		ap.setParentBillCode(bill.getBillNegotiatedId());
		List<TapDetail> list = ListUtils.newArrayList();
		for (BillNegotiatedDetail billNegotiatedDetail : bill.getBillNegotiatedDetailList()) {
			if ("1".equals(billNegotiatedDetail.getType())) {
				TapDetail detail = new TapDetail();
				detail.setCarId(bill.getCarId());
				detail.setFrameNumber(bill.getFrameNumber());
				detail.setExpenseItem("ITM00000006");
				detail.setApAmount(negotiatedAmount);
				detail.setBrand(bill.getBrand());
				detail.setArea(bill.getArea());
				detail.setModel(bill.getModel());
				list.add(detail);

				TapDetail detail1 = new TapDetail();
				detail1.setCarId(bill.getCarId());
				detail1.setFrameNumber(bill.getFrameNumber());
				detail1.setExpenseItem("ITM00000012");
				detail1.setApAmount(amount);
				detail1.setBrand(bill.getBrand());
				detail1.setArea(bill.getArea());
				detail1.setModel(bill.getModel());
				list.add(detail1);

				TapDetail detail2 = new TapDetail();
				detail2.setCarId(bill.getCarId());
				detail2.setFrameNumber(bill.getFrameNumber());
				detail2.setExpenseItem("ITM00000039");
				detail2.setApAmount(investorDetailInterestTotal);
				detail2.setBrand(bill.getBrand());
				detail2.setArea(bill.getArea());
				detail2.setModel(bill.getModel());
				list.add(detail2);

			}

		}
		ap.setTapDetailList(list);
		tapService.save(ap);
		billNegotiated.setInvestorPayableId(ap.getApId());
		billNegotiatedService.update(billNegotiated);
		return renderResult(Global.TRUE, text("资方还汇保存成功！"));
	}

	/**
	 * 保存信息
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@PostMapping(value = "confirm")
	@ResponseBody
	@Transactional(readOnly=false)
	public String confirm(BillNegotiated billNegotiated) {
		billNegotiatedService.save(billNegotiated);
		return renderResult(Global.TRUE, text("保存成功！"));
	}

	/**
	 * 批量生成页面的映射
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@RequestMapping(value = "billNegotiatedMass")
	public String billNegotiatedMass(BillNegotiated billNegotiated, Model model) {
		List<Customer> cuList = customerService.findList(new Customer());
		model.addAttribute("cuList", cuList);
		model.addAttribute("billNegotiated", billNegotiated);
		return "modules/financial/billnegotiated/billNegotiatedMassForm";
	}

	/**
	 * 批量生成
	 */

	@RequestMapping(value = "getOrderById")
	@ResponseBody
	public ServiceOrder getOrderById(@RequestParam("serviceOrderCode") String serviceOrderCode) {
		ServiceOrder serviceOrder=new ServiceOrder();
		serviceOrder.setServiceOrderId(serviceOrderCode);
//		ServiceOrder serviceOrder1 = serviceOrderService.findList(serviceOrder).get(0);
		ServiceOrder serviceOrder1 = serviceOrderService.get(serviceOrder);
		BillNegotiated billNegotiated=new BillNegotiated();
		List<ServiceOrderDetail> serviceOrderDetailList = serviceOrder1.getServiceOrderDetailList();
		List<ServiceOrderDetail> serviceOrderDetails=ListUtils.newArrayList();
		for (ServiceOrderDetail serviceOrderDetail : serviceOrderDetailList) {//循环验证该车架号是否生成过到单押汇
			billNegotiated.setServiceOrderCode(serviceOrderCode);
			billNegotiated.setFrameNumber(serviceOrderDetail.getFrameNumber());
			if(billNegotiatedService.findList(billNegotiated).size()==0)//该车架号没在到单生成过
			{
//				ladingBillService.findList()
				LadingBillDetail ladingBillDetail=new LadingBillDetail();
				ladingBillDetail.setFrameNumber(serviceOrderDetail.getFrameNumber());
				List<LadingBillDetail> list = ladingBillDetailDao.findList(ladingBillDetail);
				if(list.size()!=0)
				{
					serviceOrderDetail.setLadingBill(ladingBillService.get(list.get(0).getLadingBillId()));
				}	else {
					LadingBill ladingBill=new LadingBill();
					ladingBill.setLadingBillCode("未生成提单");
					serviceOrderDetail.setLadingBill(ladingBill);
				}
				serviceOrderDetails.add(serviceOrderDetail);
			}
		}
		serviceOrder1.setServiceOrderDetailList(serviceOrderDetails);
		return serviceOrder1;
	}

	@RequestMapping(value = "getOrderByCuId")
	@ResponseBody
	public List<ServiceOrder> getOrderListByCuId(@RequestParam("customerId") String customerId) {
		List<ServiceOrder> list = billNegotiatedDao.findList1(customerId);
		return list;
	}

	/**
	 * 生成已勾选的
	 */
	@RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
	@PostMapping(value = "creatbillNegotiatedList")
	@ResponseBody
	public String creatbillNegotiatedList(@Validated BillNegotiated billNegotiated) throws ParseException {
	List<ServiceOrderDetail> list3  =billNegotiated.getBillNegotiatedDetailList3();
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		ServiceOrder serviceOrder=new ServiceOrder();
		serviceOrder.setServiceOrderId(billNegotiated.getServiceOrderCode());
		ServiceOrder serviceOrder1 = serviceOrderService.findList(serviceOrder).get(0);//当前服务订单
		LetterCredit letterCredit=new LetterCredit();
		letterCredit.setLetterCreditId(billNegotiated.getLetterCreditCode());
		LetterCredit letterCredit11 = letterCreditService.findList(letterCredit).get(0);//当前服务订单对应的信用证对象
		LetterCredit letterCredit1 = letterCreditService.get(letterCredit11);//当前服务订单对应的信用证对象
		LadingBill ladingBill=new LadingBill();
		ladingBill.setServiceOrderId(billNegotiated.getServiceOrderCode());
		LadingBill ladingBill1 = ladingBillService.findList(ladingBill).get(0);
		//卡条件获得金融费率方案
		InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
		investorFinancialInfo.setSupplier(new Supplier(billNegotiated.getInvestorId()));//筛选资方
		investorFinancialInfo.setGroupName(billNegotiated.getCustomerRealExchangeRate());//筛选押汇方案（组合名称）
		InvestorFinancialInfo info = investorFinancialInfoService.findList(investorFinancialInfo).get(0);
		InvestorFinancialInfo investorFinancialInfo1 = investorFinancialInfoService.get(info);
		List<NegotiatedInterest> padTaxInterestList = investorFinancialInfo1.getNegotiatedInterestList();
		List<BillNegotiatedDetail> investorBillNegotiatedDetailList=ListUtils.newArrayList();//资方费率
		List<BillNegotiatedDetail> customerBillNegotiatedDetailList=ListUtils.newArrayList();//客户费率
		String investorStartDate=DateUtils.getDate1("yyyy-MM-dd",billNegotiated.getInvestorEndDate(),1, Calendar.DATE);//资方开始日期
		String customerStartDate=DateUtils.getDate1("yyyy-MM-dd",billNegotiated.getCustomerEndDate(),1, Calendar.DATE);//客户开始日期
		int i=0;//为了计数筛掉资方第一条
		int j=0;//为了计数筛掉客户第一条
		for (ServiceOrderDetail serviceOrderDetail : list3) {
			ServiceOrderDetail serviceOrderDetail1 =new ServiceOrderDetail();
			serviceOrderDetail1.setFrameNumber(serviceOrderDetail.getFrameNumber());
			ServiceOrderDetail serviceOrderDetail2 =
					serviceOrderDetailDao.findList(serviceOrderDetail1).get(0);//当前车架号对应的服务订单详情
			LetterCreditDetail letterCreditDetail=null;
			if(letterCredit1.getLetterCreditDetailList().size()!=0) {
				letterCreditDetail =
						letterCredit1.getLetterCreditDetailList().stream().
								filter(id -> id.getCarId().equals(serviceOrderDetail2.getCarId())).findFirst().get();
			}
			long investorAddDays=0;//资方天数累加
			long customerAddDays=0;//客户天数累加
			for (NegotiatedInterest padTaxInterest : padTaxInterestList) {
				//					long days = (long) NumberUtils.sub(padTaxInterest.getEndDays(), padTaxInterest.getStartDays());//发生天数
					long days = padTaxInterest.getDays() ;//本阶段天数
					BillNegotiatedDetail investorBillNegotiatedDetail = new BillNegotiatedDetail();
					BillNegotiatedDetail customerBillNegotiatedDetail = new BillNegotiatedDetail();
					if("1".equals(padTaxInterest.getStageType())) {//拆分后资方税率方案
						i++;
						investorAddDays+=padTaxInterest.getDays();
						if(i!=1) {//不是第一行
							investorBillNegotiatedDetail.setDays(days);//资方费率阶段发生天数
							investorBillNegotiatedDetail.setStartDate
									(simpleDateFormat.parse(DateUtils.getDate1("yyyy-MM-dd", billNegotiated.getStartDate(), (int) NumberUtils.sub(investorAddDays,days)+1, Calendar.DATE)));
							investorBillNegotiatedDetail.setEndDate
									(simpleDateFormat.parse(DateUtils.getDate1("yyyy-MM-dd", billNegotiated.getStartDate(), (int)investorAddDays, Calendar.DATE)));
							investorBillNegotiatedDetail.setMarginRatio(padTaxInterest.getInvestorMarginRatio());//资方保证金比例
							investorBillNegotiatedDetail.setNegotiatedRate(padTaxInterest.getInvestorInterestRatio());//资方押汇利率
							investorBillNegotiatedDetail.setMarginAmount(
									NumberUtils.mul(NumberUtils.mul(letterCreditDetail.getNegotiatedAmount(),
											Double.valueOf(padTaxInterest.getInvestorMarginRatio())),
											Double.valueOf(serviceOrder1.getTentativeExchangeRate())));//资方保证金金额
							investorBillNegotiatedDetail.setType("1");//代表资方
							investorBillNegotiatedDetailList.add(investorBillNegotiatedDetail);
						}
					}else if("2".equals(padTaxInterest.getStageType())) {//拆分后客户税率方案
                   j++;
                   customerAddDays+=padTaxInterest.getDays();
                   if(j!=1) {//不是第一行
                   	   customerBillNegotiatedDetail.setDays(days);//客户费率阶段发生天数
					   customerBillNegotiatedDetail.setStartDate
							   (simpleDateFormat.parse(DateUtils.getDate1("yyyy-MM-dd", billNegotiated.getStartDate(), (int) NumberUtils.sub(customerAddDays,days)+1, Calendar.DATE)));
					   customerBillNegotiatedDetail.setEndDate
							   (simpleDateFormat.parse(DateUtils.getDate1("yyyy-MM-dd", billNegotiated.getStartDate(), (int)customerAddDays, Calendar.DATE)));
					   customerBillNegotiatedDetail.setMarginRatio(padTaxInterest.getCustomerMarginRatio());//客户保证金比例
					   customerBillNegotiatedDetail.setNegotiatedRate(padTaxInterest.getCustomerInterestRatio());//客户押汇利率
					   customerBillNegotiatedDetail.setMarginAmount(
							   NumberUtils.mul(NumberUtils.mul(letterCreditDetail.getNegotiatedAmount(),
									   Double.valueOf(padTaxInterest.getCustomerMarginRatio())),
									   Double.valueOf(serviceOrder1.getTentativeExchangeRate())));//客户保证金金额
					   customerBillNegotiatedDetail.setType("2");
					   customerBillNegotiatedDetailList.add(customerBillNegotiatedDetail);
				   }
					}

			}
			if("on".equals(serviceOrderDetail.getTaxClearanceId()))
			{
				BillNegotiated billNegotiated1=new BillNegotiated();
				billNegotiated1.setFrameNumber(serviceOrderDetail.getFrameNumber());//车架号
				billNegotiated1.setBrand(serviceOrderDetail2.getBrand());//品牌
				billNegotiated1.setArea(serviceOrderDetail2.getArea());//版型
				billNegotiated1.setModel(serviceOrderDetail2.getModel());//车型
				billNegotiated1.setUnitPrice(serviceOrderDetail2.getUnitPrice());//价格
				billNegotiated1.setCurrency(serviceOrder1.getCurrency());//币种
				billNegotiated1.setStatus1("0");//状态
				billNegotiated1.setLetterCreditCode(letterCredit1.getLetterCreditId());//信用证编号
				billNegotiated1.setServiceOrderCode(billNegotiated.getServiceOrderCode());//
				billNegotiated1.setEntrustAgreement(letterCredit1.getEntrustAgreement());//委托协议
				billNegotiated1.setCustomerId(billNegotiated.getCustomerId());// 客户
				billNegotiated1.setCustomer(new Customer(billNegotiated.getCustomerId()));
				billNegotiated1.setInvestorId(letterCredit1.getInvestorId());	// 资方
				billNegotiated1.setForeignTradeContractNumber(letterCredit1.getForeignTradeContractNumber());// 外贸合同号
				billNegotiated1.setNegotiatedRatio(serviceOrder1.getNegotiatedRatioId());// 押汇比例
				billNegotiated1.setNegotiatedAmount(letterCreditDetail.getNegotiatedAmount());// 押汇金额
				billNegotiated1.setStartDate(billNegotiated.getStartDate());// 开始日期
				billNegotiated1.setInvestorEndDate(billNegotiated.getInvestorEndDate());// 资方结束日期
				billNegotiated1.setCustomerEndDate(billNegotiated.getCustomerEndDate());// 客户结束日期
				billNegotiated1.setN1Flag(billNegotiated.getN1Flag());// 是否N+1
//                billNegotiated1.setMarginPurchaseExchangeRate(serviceOrder1.getTentativeExchangeRate());//赋值暂定汇率作为汇率
				billNegotiated1.setTentativeExchangeRate(serviceOrder1.getTentativeExchangeRate());//暂定汇率
				billNegotiated1.setInvestorYearDays(investorFinancialInfo1.getDays());//资方年天数
				billNegotiated1.setInvestorInterestRatio(padTaxInterestList.get(0).getInvestorInterestRatio());//正常资方利息比例
				billNegotiated1.setCustomerInterestRatio(padTaxInterestList.get(0).getInvestorInterestRatio());//正常客户利息比例
				billNegotiated1.setLadingBillId(ladingBill1.getLadingBillId());//提单id
				billNegotiated1.setStatus1("1");//状态待生效
				billNegotiated1.setId(billNegotiated.getId());//附件上传
				billNegotiated1.setRowNumber(billNegotiated.getRowNumber());
				billNegotiated1.getBillNegotiatedDetailList().addAll(investorBillNegotiatedDetailList);
				billNegotiated1.getBillNegotiatedDetailList().addAll(customerBillNegotiatedDetailList);
				billNegotiatedService.save(billNegotiated1);
			}
		}

		return renderResult(Global.TRUE, text("批量生成到单押汇成功！"));
	}

	/**
	 * 通过资方id查询对应资方的押汇方案
	 */

	@RequestMapping(value = "getFinancialInfoByInId")
	@ResponseBody
	public List<InvestorFinancialInfo> tentativeExchangeRategetFinancialInfoByInId(@RequestParam("investorId") String investorId) {
		InvestorFinancialInfo investorFinancialInf=new InvestorFinancialInfo();
		investorFinancialInf.setSupplier(new Supplier(investorId));
		investorFinancialInf.setFinancingType("2");
		List<InvestorFinancialInfo> list = investorFinancialInfoService.findList(investorFinancialInf);
		return list;
	}

	/**
	 * 通过资方id查询对应资方的押汇方案
	 */

	@RequestMapping(value = "getPadTaxInterestByInId")
	@ResponseBody
	public List<List<NegotiatedInterest>> getPadTaxInterestByInId(@RequestParam("investorId") String investorId,
														@RequestParam("groupName") String groupName) {
		InvestorFinancialInfo investorFinancialInf=new InvestorFinancialInfo();
		investorFinancialInf.setSupplier(new Supplier(investorId));
		investorFinancialInf.setGroupName(groupName);
		InvestorFinancialInfo investorFinancialInfo = investorFinancialInfoService.findList(investorFinancialInf).get(0);
		List<NegotiatedInterest> negotiatedInterestList = investorFinancialInfoService.get(investorFinancialInfo).getNegotiatedInterestList();
		List<NegotiatedInterest> collect = negotiatedInterestList.stream().filter(ele -> "2".equals(ele.getStageType())).collect(Collectors.toList());
		ArrayList<List<NegotiatedInterest>> objects = ListUtils.newArrayList();
		objects.add(negotiatedInterestList);
		objects.add(collect);
		return  objects;
	}

	/**
	 * 获取资方押汇方案列表
	 *
	 * @param supplierId
	 */
	@RequestMapping(value = "getList")
	@ResponseBody
	public List<InvestorFinancialInfo> getList(@RequestParam("supplierId") String supplierId) {
		InvestorFinancialInfo info = new InvestorFinancialInfo();
		info.setInvestorName(supplierId);
		info.setFinancingType("2");
		List<InvestorFinancialInfo> list = investorFinancialInfoService.findList(info);
		return list;
	}

	/**
	 * 保证金预付
	 *
	 * @param billNegotiatedDetail
	 */

	@RequestMapping(value = "bzjyf")
	@PostMapping(value = "bzjyf")
	@ResponseBody
	@Transactional(readOnly=false)
	public String bzjyf(BillNegotiatedDetail billNegotiatedDetail) {
		BillNegotiatedDetail detail = billNegotiatedDetailDao.get(billNegotiatedDetail);
		BillNegotiated billNegotiated = billNegotiatedService.get(detail.getBillNegotiatedId());
		if(StringUtils.isEmpty(detail.getPrepaymentId())){
			//生成预付
			Tprepayment tprepayment = new Tprepayment();
			tprepayment.setSupplierId(billNegotiated.getInvestorId());
			tprepayment.setDate(new Date());
			tprepayment.setStatus1("1");
			tprepayment.setBillStatus("2");// 已提交
			tprepayment.setParentBillType("BillNegotiated");
			tprepayment.setParentBillCode(billNegotiated.getBillNegotiatedId());
			tprepayment.setServiceOrderId(billNegotiated.getServiceOrderCode());
			tprepayment.setCurrency(billNegotiated.getCurrency());
			tprepayment.setEstimatedPaymentAmount(detail.getMarginAmount());
			TprepaymentEstimated tprepaymentEstimated = new TprepaymentEstimated();
			tprepaymentEstimated.setFrameNumber(billNegotiated.getFrameNumber());
			tprepaymentEstimated.setPrepaymentType(AccountType.KZBZJ.getCode());//"ITM00000001");
			tprepaymentEstimated.setEstimatedPaymentAmount(detail.getMarginAmount());
			tprepaymentEstimated.setPaymentAmountActual(0D);
			tprepaymentEstimated.setPaymentAmountEstimated(detail.getMarginAmount());
			tprepaymentEstimated.setCarName(billNegotiated.getTcar().getCarName());
			tprepaymentEstimated.setRowNumber(billNegotiated.getRowNumber());

			tprepayment.getTprepaymentEstimatedList().add(tprepaymentEstimated);
			tprepaymentService.save(tprepayment);

			BillNegotiatedDetail d = new BillNegotiatedDetail();
			d.setBillNegotiatedDetailId(detail.getBillNegotiatedDetailId());
			d.setPrepaymentId(tprepayment.getPrepaymentId());
			billNegotiatedDetailDao.update(d);
		}
		return renderResult(Global.TRUE, text("生成成功！"));
	}

	/**
	 * 保证金预收
	 *
	 * @param billNegotiatedDetail
	 */

	@RequestMapping(value = "bzjys")
	@PostMapping(value = "bzjys")
	@ResponseBody
	@Transactional(readOnly=false)
	public String bzjys(BillNegotiatedDetail billNegotiatedDetail) {
		BillNegotiatedDetail detail = billNegotiatedDetailDao.get(billNegotiatedDetail);
		BillNegotiated billNegotiated = billNegotiatedService.get(detail.getBillNegotiatedId());
		if(StringUtils.isEmpty(detail.getPrepaymentId())){
			//生成预收
			TadvancesReceived tadvancesReceived = new TadvancesReceived();
			tadvancesReceived.setCustomerId(billNegotiated.getCustomer().getCustomerId());
			tadvancesReceived.setDate(new Date());
			tadvancesReceived.setStatus1("1");
			tadvancesReceived.setServiceOrderId(billNegotiated.getServiceOrderCode());
			tadvancesReceived.setCurrency(billNegotiated.getCurrency());
			tadvancesReceived.setBillStatus("2");// 已提交
			tadvancesReceived.setParentBillType("BillNegotiated");
			tadvancesReceived.setParentBillCode(billNegotiated.getBillNegotiatedId());
			tadvancesReceived.setEstimatedReceivedAmount(detail.getMarginAmount());
			TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
			tadvancesReceivedEstimated.setFrameNumber(billNegotiated.getFrameNumber());
			tadvancesReceivedEstimated.setAdvancesReceivedType(AccountType.KZBZJ.getCode());//"ITM00000001");
			tadvancesReceivedEstimated.setEstimatedReceivedAmount(detail.getMarginAmount());
			tadvancesReceivedEstimated.setReceivedAmountActual(0D);
			tadvancesReceivedEstimated.setReceivedAmountEstimated(detail.getMarginAmount());
			tadvancesReceivedEstimated.setCarName(billNegotiated.getTcar().getCarName());
			tadvancesReceivedEstimated.setRowNumber(billNegotiated.getRowNumber());
			tadvancesReceived.getTadvancesReceivedEstimatedList().add(tadvancesReceivedEstimated);
			tadvancesReceivedService.save(tadvancesReceived);

			BillNegotiatedDetail d = new BillNegotiatedDetail();
			d.setBillNegotiatedDetailId(detail.getBillNegotiatedDetailId());
			d.setAdvancesReceivedId(tadvancesReceived.getAdvancesReceivedId());
			billNegotiatedDetailDao.update(d);
		}
		return renderResult(Global.TRUE, text("生成成功！"));
	}

	/**
	 * 国际运输保险费
	 *
	 * @param billNegotiated
	 */
	@PostMapping(value = "inter")
	@ResponseBody
	@Transactional(readOnly=false)
	public String inter(BillNegotiated billNegotiated) {
		BillNegotiated bill = billNegotiatedService.get(billNegotiated);
		String investorId = bill.getInvestorId();
		String customerId = bill.getCustomer().getCustomerId();
		Double amount = bill.getNegotiatedAmount();// 押汇金额
		Double ratio = Double.parseDouble(bill.getInvestorRealExchangeRate());// 资方实际汇率
		FixedExpense fixedExpense = fixedExpenseService.get(AccountType.KZBZJ.getCode());//"ITM00000001");

		// 应付
		if(StringUtils.isEmpty(bill.getInterApId())){
			Double rate = 0D;
			List<SupplierPrice> collect = fixedExpense.getSupplierPriceList().stream().filter(i -> investorId.equals(i.getSupplierId())).collect(Collectors.toList());
			if(ListUtils.isNotEmpty(collect)){
				rate = NumberUtils.div(Double.parseDouble(collect.get(0).getRatio()),100);
			} else {
				rate = Double.parseDouble(fixedExpense.getPurchasePriceRatio());
			}
			Double price = NumberUtils.mul(NumberUtils.mul(amount, ratio), rate);
			Tap ap = new Tap();
			ap.setSupplierId(bill.getInvestorId());
			ap.setDate(new Date());
			ap.setStatus1("1");
			ap.setBillStatus("2");// 已提交
			ap.setServiceOrderId(bill.getServiceOrderCode());
			ap.setAmount(price);
			ap.setCurrency(bill.getCurrency());
			ap.setParentBillType("BillNegotiated");
			ap.setParentBillCode(bill.getBillNegotiatedId());
			List<TapDetail> list = ListUtils.newArrayList();
			TapDetail detail = new TapDetail();
			detail.setCarId(bill.getCarId());
			detail.setFrameNumber(bill.getFrameNumber());
			detail.setArea(bill.getArea());
			detail.setBrand(bill.getBrand());
			detail.setModel(bill.getModel());
			detail.setExpenseItem(AccountType.KZBZJ.getCode());//"ITM00000001");
			detail.setApAmount(price);
			detail.setRowNumber(bill.getRowNumber());
			list.add(detail);
			ap.setTapDetailList(list);
			tapService.save(ap);
			billNegotiated.setInterApId(ap.getApId());
			billNegotiatedService.update(billNegotiated);
		}

		// 应收
		if(StringUtils.isEmpty(bill.getInterArId())){
			Double rate = 0D;
			List<CustomerPrice> collect = fixedExpense.getCustomerPriceList().stream().filter(i -> customerId.equals(i.getCustomer().getCustomerId())).collect(Collectors.toList());
			if(ListUtils.isNotEmpty(collect)){
				rate = NumberUtils.div(Double.parseDouble(collect.get(0).getRatio()),100);
			} else {
				rate = Double.parseDouble(fixedExpense.getSalesPriceRatio());
			}
			Double price = NumberUtils.mul(NumberUtils.mul(amount, ratio), rate);
			Tar ar = new Tar();
			ar.setCustomer(bill.getCustomer());
			ar.setDate(new Date());
			ar.setStatus1("1");
			ar.setBillStatus("2");// 已提交
			ar.setServiceOrderId(bill.getServiceOrderCode());
			ar.setAmount(price);
			ar.setCurrency(bill.getCurrency());
			ar.setParentBillType("BillNegotiated");
			ar.setParentBillCode(bill.getBillNegotiatedId());
			List<TarDetail> list = ListUtils.newArrayList();
			TarDetail detail = new TarDetail();
			detail.setCarId(bill.getCarId());
			detail.setFrameNumber(bill.getFrameNumber());
			detail.setArea(bill.getArea());
			detail.setBrand(bill.getBrand());
			detail.setModel(bill.getModel());
			detail.setExpenseItem(AccountType.KZBZJ.getCode());//"ITM00000001");
			detail.setApAmount(bill.getAmount());
			detail.setRowNumber(bill.getRowNumber());
			list.add(detail);
			ar.setTarDetailList(list);
			tarService.save(ar);
			billNegotiated.setInterArId(ar.getArId());
			billNegotiatedService.update(billNegotiated);
		}
		return renderResult(Global.TRUE, text("生成成功！"));
	}


    /**
     * 作废
     */
    @RequestMapping(value = "cancel")
    @ResponseBody
    @RequiresPermissions("financial:billnegotiated:billNegotiated:cancel")
    public String cancel(@RequestParam("billNegotiatedId") String billNegotiatedId) {
        BillNegotiated billNegotiated = new BillNegotiated();
        billNegotiated.setBillNegotiatedId(billNegotiatedId);
        billNegotiated.setStatus1("2");
        billNegotiatedService.update(billNegotiated);
        return renderResult(Global.TRUE, text("作废成功！"));
    }

}